/*
*    Phantom Test Driver v2.0 GUI Automation Software
*    Copyright (C) 2009  John C. Van Arsdall (john@phantomtest.com)
*
*    This program is free software; you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation; either version 2 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License along
*    with this program; if not, write to the Free Software Foundation, Inc.,
*    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
// PTDExec.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "PTDExec.h"
#include "PTDExecDlg.h"
#include ".\ptdexec.h"
#include <direct.h>
#include "jni.h"       /* where everything is defined */


#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CPTDExecApp

BEGIN_MESSAGE_MAP(CPTDExecApp, CWinApp)
	ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()


// CPTDExecApp construction

CPTDExecApp::CPTDExecApp()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}


// The one and only CPTDExecApp object

CPTDExecApp theApp;


// CPTDExecApp initialization

BOOL CPTDExecApp::InitInstance()
{
	// InitCommonControls() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	InitCommonControls();

	CWinApp::InitInstance();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization
	SetRegistryKey(_T("Phantom Test Driver"));

	//CPTDExecDlg dlg;
	//m_pMainWnd = &dlg;
	m_pMainWnd = NULL;

	// ------- Set Starting Directory -----------------------
	char buff[4096];
	GetModuleFileName(NULL, buff, 4095);
	CString str = buff;
	str = str.Mid(0, str.ReverseFind('\\'));
	chdir((LPCTSTR)str);

	// ------- Check PTD Options ----------------------------
	CStdioFile aFile;
	if(!aFile.Open("ptd_options.dat", CFile::modeRead, NULL)){
		if(aFile.Open("ptd_options.dat", CFile::modeWrite | CFile::modeCreate, NULL)){

			buff[0] = 0;
			getcwd(buff, 4095);
			CString sAgent = buff; 
			sAgent = sAgent + "\\PhantomAgent.exe";

			DWORD Size = 4095;

			aFile.WriteString("PTD_LICENSE_KEY=\n");
      aFile.WriteString("PTD_DEFAULT_WORKSPACE=\n");
			//aFile.WriteString("PTD_DEFAULT_SUITE=\n");
			//aFile.WriteString("PTD_DEFAULT_AGENT="+sAgent+"\n");
			//aFile.WriteString("PTD_DEFAULT_AGENT_PORT=4242\n");
		
			//if(GetComputerName(buff, &Size)){
			//	sAgent = buff;
			//}	
			//aFile.WriteString("PTD_DEFAULT_MACHINE="+sAgent+"\n");

			aFile.Close();
		}
	}else{
		aFile.Close();
	}

	// ------- Start JRE with PRD ---------------------------
  
  // the -ss sets the stack size to 16 MB
	char* sCmd = ".\\jre\\bin\\javaw.exe -ss16000000 -jar PTD.jar";

	STARTUPINFO Start;
	ZeroMemory(&Start, sizeof(Start));
	Start.cb = sizeof(Start);
	if(!CreateProcess(NULL, sCmd, NULL, NULL, FALSE, NULL, NULL, NULL, &Start, &pInfo))
	{
		DWORD Err = GetLastError();
		if(Err == ERROR_FILE_NOT_FOUND)
		{
			str = str + "\\jre\\bin\\javaw.exe Not Found.  Please re-install PTD.";
			MessageBox(NULL, (LPCTSTR)str, "PTD Error", MB_OK);
			pInfo.hProcess = NULL;
			return FALSE;
		}
		else
		{
			pInfo.hProcess = NULL;
			return FALSE;
		}			
	}

  //MessageBox(NULL, "HEY", "HEY", MB_OK);

	WaitForSingleObject(pInfo.hThread, INFINITE);
	CloseHandle(pInfo.hThread);
	CloseHandle(pInfo.hProcess);
	pInfo.hProcess = NULL;

  

//    JavaVM *jvm;       /* denotes a Java VM */
//    JNIEnv *env;       /* pointer to native method interface */
//    JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
//    JavaVMOption* options = new JavaVMOption[1];

    //options[0].optionString = "-Djava.class.path=/usr/lib/java";
    //options[0].optionString = "-Djava.class.path=c:/Projects/Java/PTD/dist";
    //options[0].optionString = "-Djava.class.path=C:/Progra~1/Java/jre1.5.0_12/lib";
//    options[0].optionString = "-Djava.class.path=C:\\Projects\\Java\\PTD\build\\classes";
    //C:\Projects\Java\PTD\build\classes
//    vm_args.version = JNI_VERSION_1_2;
//    vm_args.nOptions = 1;
//    vm_args.options = options;
//    vm_args.ignoreUnrecognized = false;
    /* load and initialize a Java VM, return a JNI interface
     * pointer in env */
//    jint res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
//    
//    delete options;

//    if(res != 0){
//      return FALSE;
//    }

    /* invoke the Main.test method using the JNI */
//    jclass cls = env->FindClass("Main");
    //jmethodID mid = env->GetStaticMethodID(cls, "test", "(I)V");
//    jmethodID mid = env->GetStaticMethodID(cls, "jvm_main", "(V)V");
//    env->CallStaticVoidMethod(cls, mid, 100);
    /* We are done. */
//    jvm->DestroyJavaVM();



	/*
	INT_PTR nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel
	}
	*/

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}

int CPTDExecApp::ExitInstance()
{
	// TODO: Add your specialized code here and/or call the base class
	if(pInfo.hProcess != NULL){
		TerminateProcess(pInfo.hProcess, 0);
	}
	pInfo.hProcess = NULL;
	return CWinApp::ExitInstance();
}
